package OptimalAlgorithm.TwoPointTechnique;
//给你一个长度固定的整数数组 arr ，请你将该数组中出现的每个零都复写一遍，并将其余的元素向右平移。
//eg:
//输入：arr = [1,0,2,3,0,4,5,0]
//输出：[1,0,0,2,3,0,0,4]
public class DuplicateZeros {
    public void duplicateZeros(int[] arr) {
        int cur = 0;
        int dest = -1;
        //找到最后复写的数
        while (cur < arr.length){
            if(arr[cur] == 0 ){
                dest += 2;
            }else {
                dest += 1;
            }
            if(dest >= arr.length - 1){
                break;
            }
            cur++;
        }
        //处理dest越界的情况，eg：[1,0,2,3,0,4]
        if(dest == arr.length){
            arr[arr.length - 1] = 0;
            dest -= 2;
            cur--;
        }
        while (cur >= 0){
            if(arr[cur] != 0){
                arr[dest] = arr[cur];
            }else {
                arr[dest] = 0;
                dest--;
                arr[dest] = 0;
            }
            dest--;
            cur--;
        }
    }
}
